package com.maixy.dailydemo.thread;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @ClassName ThreadTest
 * @Description TODO
 * @Date 2021/9/15 14:13
 * @Author NINGMEI
 */
@Slf4j
@RestController
@RequestMapping("/threadTest")
public class ThreadTest {
    public final static List<Integer> userIdList = new ArrayList<>();
//    public static void main(String[] args) {
//        for (int i = 0; i < 890; i++) {
//            userIdList.add(i);
//        }
//        updateFirstBuyTime();
//    }

    @GetMapping("/updateFirstBuyTime")
    public void updateFirstBuyTime() {
        for (int i = 0; i < 890; i++) {
            userIdList.add(i);
        }
        log.info("----------------------------修改用户第一次购物时间开始----------------------------");
        Integer userId = 0;
        ExecutorService executorService = Executors.newWorkStealingPool(3);
        for (int i = 0; i < 100000; i++) {
            log.info("----------------------------当前userId:{}----------------------------", userId);
            List<Integer> userList = findUser(userId);
            log.info(userList.toString());
            handle(executorService, userList);
            if(userList.size() > 0) {
                userId = userList.get(userList.size() - 1);
            }
            //说明没有下一页了，停止循环
            if (100 > userList.size()) {
                break;
            }
        }
        log.info("----------------------------修改用户第一次购物时间结束----------------------------");
    }

    private static List<Integer> findUser(Integer userId) {
        int first;
        int last;
        if (userId == 0) {
            first = 0;
            last = userId + 100;
        } else {
            first = userId + 1;
            last = userId + 101;
        }
        if (last > userIdList.size() - 1) {
            last = userIdList.size() - 1;
        }
        return userIdList.subList(first, last);
    }

    private static void handle(ExecutorService executorService, List<Integer> userList) {
        executorService.submit(() -> {
            for (Integer userId : userList) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                log.info("用户：{}", userId);
            }
        });
    }
}
